package fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import mindshare.Distance;
import mindshare.FriendRequest;
import mindshare.LoadContent;
import mindshare.FriendsListAdapter;
import mindshare.SessionManager;
import info.androidhive.slidingmenu.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Context;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationManager;

public class FriendsFragment extends Fragment implements LocationListener {
	private List<FriendRequest> friendList = new ArrayList<FriendRequest>(), friendRequestList = new ArrayList<FriendRequest>(), 
			locationList = new ArrayList<FriendRequest>(), suggestionList = new ArrayList<FriendRequest>();
	private TabHost th;
	private Context c;
	private View rootView;
	private MenuItem refreshMenuItem;
	private String userLocation, name;
	
	SessionManager session;
	List<NameValuePair> params = new ArrayList<NameValuePair>();

	// Mel
	protected LocationManager locationManager;
	protected LocationListener locationListener;
	protected Context context;
	String lat;
	String provider;
	protected String latitude, longitude;
	protected boolean gps_enabled, network_enabled;

	public FriendsFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_friends, container, false);
		c = rootView.getContext();
		session = new SessionManager(c);
		session.checkLogin();
		HashMap<String, String> user = session.getUserDetails();
		name = user.get(SessionManager.KEY_NAME);
		th = (TabHost) rootView.findViewById(android.R.id.tabhost);
		th.setup();
		TabSpec specs = th.newTabSpec("friends");
		specs.setContent(R.id.tabFriends);
		specs.setIndicator("Friends");
		th.addTab(specs);
		specs = th.newTabSpec("fRequest");
		specs.setContent(R.id.tabFriendRequests);
		specs.setIndicator("Friend Requests");
		th.addTab(specs);
		specs = th.newTabSpec("suggestions");
		specs.setContent(R.id.tabSuggestions);
		specs.setIndicator("Suggestions");
		th.addTab(specs);
		th.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				if ("friends".equals(tabId)) {
					friendsTask();
				}
				if ("fRequest".equals(tabId)) {
					friendRequestTask();
				}
				if ("suggestions".equals(tabId)) {
					suggestionsTask();
				}
			}
		});
		
		locationManager = (LocationManager) c.getSystemService(c.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

		setHasOptionsMenu(true);
		return rootView;
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.f_request_menu, menu);
		
		refreshMenuItem = menu.findItem(R.id.empty_sea);
		SearchManager searchManager = (SearchManager) c.getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(((Activity) c).getComponentName()));
		friendsTask();
		super.onCreateOptionsMenu(menu, inflater);
	}

	// Mel
	@Override
	public void onLocationChanged(Location location) {
		Distance d = new Distance(location.getLatitude(), location.getLongitude(), getActivity());
		setUserLocation(d.getCurrentLocation());
		Log.d("People location", d.getCurrentLocation());
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.d("Latitude", "disable");
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.d("Latitude", "enable");
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.d("Latitude", "status");
	}

	public String getUserLocation() {
		return userLocation;
	}

	public void setUserLocation(String userLocation) {
		this.userLocation = userLocation;
	}

	public void friendsTask(){
		params.clear();
		params.add(new BasicNameValuePair("nickname", name));
		(new LoadFriends(c, params, "friends")).execute();
	}
	
	public void friendRequestTask(){
		params.clear();
		params.add(new BasicNameValuePair("nickname", name));
		(new LoadFriendRequests(c, params, "friends")).execute();
	}
	
	public void suggestionsTask(){
		if(getUserLocation()!=null){
			params.clear();
			params.add(new BasicNameValuePair("location", getUserLocation()));
			(new LoadLocationSuggestions(c, params, "friends")).execute();
		}
	}
	

	class LoadFriendRequests extends LoadContent {
		Context c;

		public LoadFriendRequests(Context context, List<NameValuePair> param, String data) {
			super(context, param, data);
			this.c = context;
		}
		
		@Override
	    protected void onPreExecute() {
			refreshMenuItem.setActionView(R.layout.action_progressbar);
			refreshMenuItem.expandActionView();
	    }

		@Override
		protected String doInBackground(String... args) {
			JSONObject json = jParser.makeHttpRequest(url + "getFriendRequest.php", param);
			JSONArray friends;
			friendRequestList.clear();
			try {
				friends = json.getJSONArray(data);
				for (int i = 0; i < friends.length(); i++) {
					JSONArray friends2 = friends.getJSONArray(i);
					friendRequestList.add(new FriendRequest(friends2.getString(0), friends2.getString(1), friends2.getString(3), friends2.getString(2)));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String file_url) {
			ListView lv = (ListView) ((Activity) c) .findViewById(R.id.listView1);
			lv.setAdapter(new FriendsListAdapter(c, R.layout.friendtable_add_delete, friendRequestList, refreshMenuItem));
			lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent,
						View viewClicked, int position, long id) {
					FriendRequest clickedFriend = friendRequestList.get(position);
					String message = "You clicked position " + position + " Which name is " + clickedFriend.getUserName();
					Toast.makeText(c, message, Toast.LENGTH_LONG).show();
					Log.d("MESSAGE", message);
				}
			});
			refreshMenuItem.collapseActionView();
			refreshMenuItem.setActionView(null);
		}
	}
	
	class LoadLocationSuggestions extends LoadContent {
		Context c;

		public LoadLocationSuggestions(Context context, List<NameValuePair> param, String data) {
			super(context, param, data);
			this.c = context;
		}

		@Override
	    protected void onPreExecute() {
			refreshMenuItem.setActionView(R.layout.action_progressbar);
			refreshMenuItem.expandActionView();
	    }
		
		@Override
		protected String doInBackground(String... args) {
			JSONObject json = jParser.makeHttpRequest(url + "getLocationSuggestion.php", param);
			JSONArray friends;
			locationList.clear();
			try {
				friends = json.getJSONArray(data);
				for (int i = 0; i < friends.length(); i++) {
					JSONArray friendsLoc = friends.getJSONArray(i);
					locationList.add(new FriendRequest(friendsLoc.getString(0), friendsLoc.getString(1), friendsLoc.getString(2)));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String file_url) {
			ListView lv = (ListView) ((Activity) c).findViewById(R.id.lvLocationSugg);
			lv.setAdapter(new FriendsListAdapter(c, R.layout.friendtable, locationList, refreshMenuItem));
			lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
					FriendRequest clickedFriend = locationList.get(position);
					String message = "You clicked position " + position + " Which name is " + clickedFriend.getUserName();
					Toast.makeText(c, message, Toast.LENGTH_LONG).show();
					Log.d("MESSAGE", message);
				}
			});
			refreshMenuItem.collapseActionView();
			refreshMenuItem.setActionView(null);
		}
	}
	
	class LoadFriends extends LoadContent {
		Context c;

		public LoadFriends(Context context, List<NameValuePair> param, String data) {
			super(context, param, data);
			this.c = context;
		}
		
		@Override
	    protected void onPreExecute() {
			refreshMenuItem.setActionView(R.layout.action_progressbar);
			refreshMenuItem.expandActionView();
	    }

		@Override
		protected String doInBackground(String... args) {
			JSONObject json = jParser.makeHttpRequest(url + "getFriends.php", param);
			JSONArray friends;
			friendList.clear();
			try {
				friends = json.getJSONArray(data);
				for (int i = 0; i < friends.length(); i++) {
					JSONArray friendsLoc = friends.getJSONArray(i);
					friendList.add(new FriendRequest(friendsLoc.getString(0), friendsLoc.getString(1), friendsLoc.getString(2)));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String file_url) {
			ListView lv = (ListView) ((Activity) c).findViewById(R.id.lvFriends);
			lv.setAdapter(new FriendsListAdapter(c, R.layout.friendtable_delete, friendList, refreshMenuItem));
			lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
					FriendRequest clickedFriend = friendList.get(position);
					String message = "You clicked position " + position + " Which name is " + clickedFriend.getUserName();
					Toast.makeText(c, message, Toast.LENGTH_LONG).show();
					Log.d("MESSAGE", message);
				}
			});
			refreshMenuItem.collapseActionView();
			refreshMenuItem.setActionView(null);
		}
	}
}
